<template>
  <el-form ref="loginRef" :model="loginForm" :rules="rules" label-width="0" size="large" @keyup.enter="handleLogin">
    <el-form-item v-if="tenantEnabled" prop="tenantid">
      <el-select v-model="loginForm.tenantId" filterable placeholder="请选择" style="width: 100%">
        <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" prefix-icon="User" clearable :placeholder="$t('login.PWPlaceholder')"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" prefix-icon="Lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
    </el-form-item>
    <el-form-item v-if="captchaEnabled" prop="code">
      <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="请输入验证码" style="width: 67%">
        <!-- <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template> -->
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" class="login-code-img" @click="getCode" />
      </div>
    </el-form-item>

    <el-form-item style="margin-bottom: 10px">
      <el-col :span="12">
        <el-checkbox :label="$t('login.rememberMe')" v-model="loginForm.autologin"></el-checkbox>
      </el-col>
      <el-col :span="12" class="login-forgot">
        <router-link to="/reset_password">{{ $t("login.forgetPassword") }}？</router-link>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" style="width: 100%" :loading="islogin" round @click="handleLogin(loginRef)">
        {{ $t("login.signIn") }}
      </el-button>
    </el-form-item>
    <div class="login-reg">
      {{ $t("login.noAccount") }}
      <router-link to="/user_register">{{ $t("login.createAccount") }}</router-link>
    </div>
  </el-form>
</template>

<script setup>
import { useI18n } from "vue-i18n";
import router from "@/router";
import { getMenuApi, loginApi, getTenantListApi, getCodeImgApi } from "@/api/modules/auth";
import { useAuthStore } from "@/store/modules/auth";
import { useMenuStore } from "@/store/modules/menu";

const { t } = useI18n();

const authStore = useAuthStore();

const menuStore = useMenuStore();

// 验证码开关
const captchaEnabled = ref(true);

// 租户开关
const tenantEnabled = ref(true);

// 登录状态
const islogin = ref(false);

// 租户列表数据
const tenantList = ref([]);

// 验证码地址
const codeUrl = ref("");

// 登录表单ref
const loginRef = ref();

// 表单信息
const loginForm = reactive({
  tenantId: "000000",
  username: "admin",
  password: "123456",
  autologin: false,
  rememberMe: false,
  code: "",
  uuid: "",
});

/**
 * @description 表单验证规则
 */
const rules = reactive({
  username: [{ required: true, message: t("login.userError"), trigger: "blur" }],
  password: [{ required: true, message: t("login.PWError"), trigger: "blur" }],
});

/**
 * @description 登录
 * @param formEl
 */
const handleLogin = async (formEl) => {
  if (!formEl) return;
  // 验证表单
  await formEl.validate(async (valid) => {
    if (!valid) return;
    islogin.value = true;

    try {
      // 获取 token
      const authData = await loginApi(loginForm);
      authStore.token = authData.data.token;
      authStore.userInfo = authData.data.userInfo;

      // 获取菜单
      let menuData = await getMenuApi();
      if (menuData.data.menu.length === 0) {
        islogin.value = false;
        alert("当前用户无任何菜单权限，请联系系统管理员");
        return;
      }
      menuStore.list = menuData.data.menu;
      menuStore.permissions = menuData.data.permissions;

      router.replace({ path: "/" });
      ElMessage.success("登录成功");
      islogin.value = false;
    } catch (error) {
      islogin.value = false;
    }
  });
};

/**
 * @description 初始化租户列表
 * @param {Boolean} isToken 是否需要token
 */
const initTenantList = async () => {
  const { data } = await getTenantListApi();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * @description 获取验证码
 */
const getCode = async () => {
  const { data } = await getCodeImgApi();
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = "data:image/gif;base64," + data.img;
    loginForm.uuid = data.uuid;
  }
};

// 挂在后执行
onMounted(() => {
  getCode();
  initTenantList();
});
</script>
<style lang="scss" scoped>
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  padding-left: 26px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 40px;
}
</style>
